package edu.tgc.web.controller.system;

import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;

import org.abyss.common.exception.ServiceException;
import org.abyss.common.web.controller.easyui.CommonCrudEasyUiController;
import org.abyss.common.web.controller.easyui.EasyuiResultBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import edu.tgc.entity.system.SysPermission;
import edu.tgc.entity.system.SysRole;
import edu.tgc.service.system.SysRoleService;
import edu.tgc.web.form.system.SysRoleForm;

@Controller
@RequestMapping(value = "sys/role")
public class SysRoleController extends CommonCrudEasyUiController<SysRole, UUID, SysRoleForm> {

    @Autowired
    protected SysRoleService sysRoleService;

    @Override
    protected void buildIgnoreProperties(Collection<String> ignoreProperties) {
        ignoreProperties.add("permissions");
        ignoreProperties.add("users");
    }

    @ResponseBody
    @RequestMapping(value = "permission/selected")
    public Object getPermissions(String joinIds) {
        Set<SysPermission> result = new HashSet<>();
        if (joinIds != null) {
            for (String entityId : joinIds.split(",")) {
                SysRole entity = this.baseService.getById(UUID.fromString(entityId));
                result.addAll(entity.getPermissions());
            }
        }
        return result;
    }

    @ResponseBody
    @RequestMapping(value = "permission", method = RequestMethod.POST)
    public Object permission(SysRoleForm form, BindingResult bindingResult, Model model, RedirectAttributes redirectAttributes) {
        if (bindingResult.hasErrors()) {
            return EasyuiResultBuilder.buildAjaxResultError(bindingResult.getGlobalError().getDefaultMessage());
        } else {
            try {
                this.sysRoleService.setPermissions(form.getId(), form.getPermissionIds());
            } catch (ServiceException e) {
                return EasyuiResultBuilder.buildAjaxResultError(e.getMessage());
            }
        }
        return EasyuiResultBuilder.buildAjaxResult();
    }
}
